package com.lzc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lzc.domain.MigrationProgress;
import com.lzc.mapper.MigrationProgressMapper;
import com.lzc.service.MigrationProgressService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * 迁移进度服务实现类
 */
@Slf4j
@Service
public class MigrationProgressServiceImpl extends com.baomidou.mybatisplus.extension.service.impl.ServiceImpl<MigrationProgressMapper, MigrationProgress>
    implements MigrationProgressService {

    @Autowired
    private MigrationProgressMapper migrationProgressMapper;

    @Override
    public MigrationProgress getOrCreateProgress(String taskName, String sourceTable, String targetTable, 
                                               Long totalCount, Integer batchSize) {
        // 查询现有进度记录
        LambdaQueryWrapper<MigrationProgress> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(MigrationProgress::getTaskName, taskName);
        MigrationProgress existingProgress = this.getOne(queryWrapper);
        
        if (existingProgress != null) {
            log.info("找到现有迁移进度: 任务={}, 已处理ID={}, 已处理记录数={}", 
                    taskName, existingProgress.getMaxProcessedId(), existingProgress.getProcessedCount());
            return existingProgress;
        }
        
        // 创建新的进度记录
        MigrationProgress progress = new MigrationProgress();
        progress.setTaskName(taskName);
        progress.setSourceTable(sourceTable);
        progress.setTargetTable(targetTable);
        progress.setMaxProcessedId(0L);
        progress.setProcessedCount(0L);
        progress.setTotalCount(totalCount);
        progress.setBatchSize(batchSize);
        progress.setStatus("RUNNING");
        progress.setStartTime(LocalDateTime.now());
        progress.setCreateTime(LocalDateTime.now());
        progress.setUpdateTime(LocalDateTime.now());
        
        this.save(progress);
        log.info("创建新的迁移进度记录: 任务={}, 总记录数={}, 批处理大小={}", 
                taskName, totalCount, batchSize);
        
        return progress;
    }

    @Override
    public void updateProgress(String taskName, Long maxProcessedId, Long processedCount) {
        LambdaQueryWrapper<MigrationProgress> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(MigrationProgress::getTaskName, taskName);
        
        MigrationProgress progress = this.getOne(queryWrapper);
        if (progress != null) {
            progress.setMaxProcessedId(maxProcessedId);
            progress.setProcessedCount(processedCount);
            progress.setUpdateTime(LocalDateTime.now());
            this.updateById(progress);
            
            // 每更新10000条记录输出一次进度
            if (processedCount % 10000 == 0) {
                double percent = progress.getTotalCount() != null && progress.getTotalCount() > 0
                        ? (double) processedCount * 100.0 / progress.getTotalCount()
                        : 0.0;
                String percentStr = String.format("%.2f", percent);
                log.info("迁移进度更新: 任务={}, 已处理ID={}, 已处理记录数={}, 进度={}%%", 
                        taskName, maxProcessedId, processedCount, percentStr);
            }
        }
    }

    @Override
    public void completeTask(String taskName) {
        LambdaQueryWrapper<MigrationProgress> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(MigrationProgress::getTaskName, taskName);
        
        MigrationProgress progress = this.getOne(queryWrapper);
        if (progress != null) {
            progress.setStatus("COMPLETED");
            progress.setEndTime(LocalDateTime.now());
            progress.setUpdateTime(LocalDateTime.now());
            this.updateById(progress);
            log.info("迁移任务完成: 任务={}, 总处理记录数={}", taskName, progress.getProcessedCount());
        }
    }

    @Override
    public void failTask(String taskName, String errorMessage) {
        LambdaQueryWrapper<MigrationProgress> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(MigrationProgress::getTaskName, taskName);
        
        MigrationProgress progress = this.getOne(queryWrapper);
        if (progress != null) {
            progress.setStatus("FAILED");
            progress.setErrorMessage(errorMessage);
            progress.setEndTime(LocalDateTime.now());
            progress.setUpdateTime(LocalDateTime.now());
            this.updateById(progress);
            log.error("迁移任务失败: 任务={}, 错误信息={}", taskName, errorMessage);
        }
    }

    @Override
    public void resetTask(String taskName) {
        LambdaQueryWrapper<MigrationProgress> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(MigrationProgress::getTaskName, taskName);
        
        MigrationProgress progress = this.getOne(queryWrapper);
        if (progress != null) {
            progress.setMaxProcessedId(0L);
            progress.setProcessedCount(0L);
            progress.setStatus("RUNNING");
            progress.setStartTime(LocalDateTime.now());
            progress.setEndTime(null);
            progress.setErrorMessage(null);
            progress.setUpdateTime(LocalDateTime.now());
            this.updateById(progress);
            log.info("重置迁移任务: 任务={}", taskName);
        }
    }
}
